const db=require('../db/index');
const bcrypt=require('bcryptjs');
exports.getInfo=(req,res)=>{
  console.log(req.user);
  const sql='select id,username,password,nickname,email,user_pic from ev_users where id=?'
  db.query(sql,req.user.id,(err,result)=>{
    if(err){
      return res.cc(err)
    }
    if(result.length!==1){
      return res.cc('获取信息失败');
    }
    // console.log(req);
    res.send({
      status:0,
      message:'用户信息获取成功',
      data:req.user//要发送给客户端的用户信息
    })
  })
}
exports.updateUserInfo=(req,res)=>{
  const sql='update ev_users set ? where id=?';
  db.query(sql,[req.body,req.body.id],(err,result)=>{
    if(err){return res.cc(err);}
    if(result.affectedRows!==1){return res.cc('修改用户信息失败');}
    res.cc('修改用户信息成功',0);
  })
}
exports.updatePwd=(req,res)=>{
  const sql=`select * from ev_users where id=?`;
  db.query(sql,req.user.id,(err,result)=>{
    if(err){return res.cc(err)}
    if(result.length!==1){return res.cc('用户不存在')}
    const compareResult=bcrypt.compareSync(req.body.oldpwd,result[0].password);
    if(!compareResult){return res.cc('原密码错误')}
    const newpwd=bcrypt.hashSync(req.body.newpwd,10);
    const sql1=`update ev_users set password=? where id=?`;
    db.query(sql1,[newpwd,req.user.id],(err,result)=>{
      if(err){return res.cc(err)}
      if(result.affectedRows!==1){return res.cc('修改密码失败')}
      res.cc('修改密码成功',0)
    })
  })
}
exports.updateAvatar=(req,res)=>{
  const sql='update ev_users set user_pic=? where id =?';
  db.query(sql,[req.body.user_pic,req.user.id],(err,result)=>{
    if(err){return res.cc(err)}
    if(result.affectedRows!==1){return res.cc('更新头像失败')}
    res.cc('头像更新成功',0);
  })
}